import configs from '@/common/config.js'
import {
	colorStore
} from "/store/color"

export default {
	hexToRgb(hex, opacity = 1) {
		// 去除#号
		var color = hex.replace('#', '');
		// 分割成红、绿、蓝三部分的16进制字符串
		var red = parseInt(color.substring(0, 2), 16);
		var green = parseInt(color.substring(2, 4), 16);
		var blue = parseInt(color.substring(4, 6), 16);

		return `rgba(${red}, ${green}, ${blue},${opacity})`;
	},
	colorObj() {
		const bgColor = colorStore()
		return bgColor.list
	},
	
	// #ifdef MP-WEIXIN
	//获取小程序胶囊信息
	getWXStatusHeight() {
		// 获取距上
		const barTop = wx.getSystemInfoSync().statusBarHeight
		// 获取胶囊按钮位置信息
		const menuButtonInfo = wx.getMenuButtonBoundingClientRect()
		// 获取导航栏高度
		const barHeight = menuButtonInfo.height + (menuButtonInfo.top - barTop) * 2
		let barWidth = menuButtonInfo.width

		return {
			barHeight,
			barTop,
			barWidth
		}
	},
	// #endif
	
	safeT() {
		return uni.getSystemInfoSync().statusBarHeight + 10 + 'px'
	},
	oss(url) {
		if (!url) {
			return ''
		}
		if (typeof url === 'string') {
			if ((/^(http|https):\/\/.+/.test(url))) {
				return url
			} else if ((/^(data:image).+/.test(url))) {
				return url
			} else {
				return configs.imgUrl + url
			}
		} else {
			let arr = []
			for (let i = 0; i < url.length; i++) {
				if ((/^(http|https):\/\/.+/.test(url[i]))) {
					arr.push(url[i])
				} else {
					arr.push(configs.imgUrl + url[i])
				}
			}
			return arr
		}
	},
	skip(url, events = {}, success) {
		uni.navigateTo({
			url,
			events,
			success
		})
	},
	back(delta = 1) {
		uni.navigateBack({
			delta: delta
		})
	},
	authTo(url) {
		if (uni.getStorageSync('token')) {
			uni.navigateTo({
				url: url
			});
		} else {
			uni.navigateTo({
				url: configs.login
			});
		}
	},
	login() {
		uni.navigateTo({
			url: configs.login
		});
	},
	toast(word) {
		uni.$u.toast(word);
	},
	call(tel) {
		uni.makePhoneCall({
			phoneNumber: tel
		});
	},
	map(lat, lng, name) {
		console.log(lat, lng)
		uni.openLocation({
			latitude: Number(lat),
			longitude: Number(lng),
			name: name,
			success: function() {
				console.log('success');
			},
			fail(e) {
				console.log(e);
			}
		});
	},
	copy(content) {
		uni.setClipboardData({
			data: content,
			success: function() {
				uni.$u.toast('复制成功')
			},
			fail: function() {
				uni.$u.toast('复制失败')
			}
		});
	},

	chooseImage(count = 1, source = ['album', 'camera'], token, loading = true,
		toast = true, sizeType = 'original') {
		return new Promise((resolve, reject) => {
			uni.chooseImage({
				count: count,
				sourceType: source,
				sizeType: sizeType ? sizeType : ['compressed'],
				success: async (res) => {
					console.log(res, '....')
					let arr = [];
					for (let i = 0; i < res.tempFiles.length; i++) {
						let result = await upload(res.tempFilePaths[i], {
							type: 'image',
							token: token
						}, loading, toast)
						arr.push(result)
					}
					resolve(arr)

				},
				fail: (err) => {
					console.log(err)
					reject(err)
				}
			})
		})
	},

	chooseVideo(count = 1, source = ['album', 'camera'], token, loading = true,
		toast = true, sizeType = 'original') {
		return new Promise((resolve, reject) => {
			uni.chooseVideo({
				count: count,
				sourceType: source,
				sizeType: sizeType ? sizeType : ['compressed'],
				success: async (res) => {
					let arr = [];
					let result = await upload(res.tempFilePath, {
						type: 'video',
						token: token
					}, loading, toast)
					arr.push(result)
					resolve(arr)
				},
				fail: (err) => {
					console.log(err)
					reject(err)
				}
			})
		})
	},

	getLocation(lat = '', lng = '') {
		return new Promise((resolve, reject) => {
			uni.getLocation({
				type: 'wgs84',
				success: (res) => {
					let lat = res.latitude
					let lng = res.longitude
					$api.post('user/getlocation', {
						lat: res.latitude,
						lng: res.longitude
					}).then(res => {
						if (res.data == false) {
							uni.showModal({
								title: '提示',
								content: '获取位置失败',
								showCancel: false, //没有取消按钮的弹框
								buttonText: '确定',
								success: function(res) {
									if (res.confirm) {
										console.log('用户点击确定');
									} else if (res.cancel) {
										console.log('用户点击取消');
									}
								}
							});
							return
						}
						let city = ''
						let province = res.data.regeocode.addressComponent.province
						if (res.data.regeocode.addressComponent.city === '[]' || res.data
							.regeocode.addressComponent.city.length === 0) {
							city = province
						} else {
							city = res.data.regeocode.addressComponent.city
						}
						let district = res.data.regeocode.addressComponent.district
						let name = (res.data.regeocode.aois[0] && res.data.regeocode.aois[0]
							.name) || res.data.regeocode.formatted_address
						let data = {
							city,
							province,
							district,
							name,
							lat,
							lng
						}
						resolve(data)
					}).catch(err => {
						reject(err)
					})
				},
				fail: (e) => {
					console.log(e, '????')
					uni.showModal({
						title: '您未开启地理位置授权',
						content: '请在设置中打开位置授权，以便我们能够更好的提供服务',
						success(res) {
							if (res.confirm) {
								uni.openSetting()
							} else if (res.cancel) {
								let data = {
									province: '河南省',
									city: '郑州市',
									district: '中原区',
									name: '郑州市',
									lat: '34.74725',
									lng: '113.62493'
								}
								reject(data)
							}
						}
					})
					return
					uni.getSetting({
						withSubscriptions: true,
						success: (res) => {
							let authSetting = res.authSetting
							if (!authSetting['scope.userLocation']) {
								uni.showModal({
									title: '您未开启地理位置授权',
									content: '请在设置中打开位置授权，以便我们能够更好的提供服务',
									success(res) {
										if (res.confirm) {
											uni.openSetting()
										} else if (res.cancel) {
											let data = {
												province: '河南省',
												city: '郑州市',
												district: '中原区',
												name: '郑州市',
												lat: '34.74725',
												lng: '113.62493'
											}
											reject(data)
										}
									}
								})
							}
						}
					})
				}
			})
		})
	}
}


const upload = (file, data, loading = false, is_toast = true) => {
	return new Promise((resolve, reject) => {
		if (loading) {
			uni.showLoading({
				title: '加载中',
				mask: true,
			})
		}
		let url = '/api/post'
		let info = (data && data.token) ? data : {
			...data,
			token: uni.getStorageSync('token') ? uni.getStorageSync('token') : '',
		}
		console.log(info)
		uni.uploadFile({
			url: configs.baseUrl + url, //仅为示例，非真实的接口地址
			filePath: file,
			name: 'file',
			formData: {
				...info
			},
			success: (result) => {
				result.data = JSON.parse(result.data)
				console.log()
				if (result.statusCode === 401) {
					uni.navigateTo({
						url: '/pages_login/login',
					})
					reject(result)
				}

				if (result.data.code !== 1) {
					if (is_toast) {
						toast((result && result.data && result.data.msg) ? result.data.msg :
							'请稍后重试')
					}
					reject(result)
				}
				resolve(result.data.data)
			},
			fail: (res) => {

				reject(res)
			},
			complete: (res) => {
				uni.hideLoading()
			},
		})

	})
}